/**
 * 
 */
package pt.inescid.utils;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * @author Sergio Esteves (sesteves at gsd.inesc-id.pt)
 *
 */
public class ReadXML {
	
	private Document doc;
	
	public ReadXML(String fileName) {
		try {
			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();					
			doc = docBuilder.parse(new File(fileName));
			doc.getDocumentElement ().normalize ();
								
		} catch (ParserConfigurationException e) {
			System.err.println("Error: " + e.getMessage());
		} catch (IOException e) {
			System.err.println("Error: " + e.getMessage());
		} catch (SAXException e) {
			System.err.println("Error: " + e.getMessage());
		}	
	}
	
	/**
	 * 
	 * @param tagname
	 * @param position
	 * @return value of the tag; null otherwise
	 */
	public String getTag(String tagname, int position) {
		NodeList lst = doc.getElementsByTagName(tagname);
		
		Element elem = (Element)lst.item(position);
		if(elem == null || elem.getChildNodes().item(0) == null) 
			return null;
		return elem.getChildNodes().item(0).getNodeValue().trim();			
	}
}
